<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page language="java" import="java.lang.*" %>
<%@ page import = "java.sql.SQLException" %>
<%@ page import = "com.seniorproject.aims.*" %>
<%@ page import = "java.util.List" %>
<%@page import="java.util.ArrayList"%>
<%@ page import = "java.util.Properties" %>
<%@ page import = "javax.servlet.ServletContext" %>
<%@ page import = "java.io.File" %>
<%@ page import = "java.io.InputStream" %>
<%@ page import = "java.util.List" %>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.Date"%>
<%@ page import = "java.util.Properties" %>
<%@ page import = "javax.servlet.ServletContext" %>
<%@ page import = "java.io.File" %>
<%@ page import = "java.io.InputStream" %>
<%@ page import = "java.io.FileInputStream" %>
<%@ page import = "java.sql.PreparedStatement" %>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Add Employee</title>
	
<link rel="stylesheet" type="text/css" href="css/stylev2.css" />
<link rel="stylesheet" type="text/css" href="css/frame2.css" />
<link rel="stylesheet" href="css/jquery.mobile-1.3.2.min.css"/>	
<link rel="stylesheet" href="css/redmond/jquery-ui.css" type="text/css"/>
	
<style type="text/css">
	a {
      text-decoration:none;
   	}
   	td:nth-child(odd) {
		font-weight: bold;
	}
	td {
		height: 50px;
	}
	.silvergrad:hover {
	    cursor: pointer;
	}
</style>
<script type="text/javascript" src="js/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="js/bootbox.js"></script>
<script src="js/jquery.ajaxfileupload.js"></script>
<script>
$(document).ready(function(){
	var patt = new RegExp("[#$%^*?!~`<>]");
	$("#frm_add_file").hide();
	$("#import_excel").click(function(){
		 
					$("#frm_add_file").toggle();
		 
	 });
	$('input[type="file"]').ajaxfileupload({
		'action' : 'UploadServletLecturerAddNormal',
		'onComplete' : function(response) {
			$('#upload').hide();
			$('#message').show();
			
			var statusVal = JSON.stringify(response.status);

			if(statusVal == "false")
			{
				$("#message").html("<font color='red'>"+ JSON.stringify(response.message) +" </font>");
				
			}	
			if(statusVal == "true")
			{
				$("#message").html("<font color='green'>"+ JSON.stringify(response.message) +" </font>");
			}			
		},
		'onStart' : function() {
			$('#upload').show();
			$('#message').hide();
		}
	});
	

	$('#save').click(function(){
		 var check = "";
		 var error = "กรุณากรอก";
		 
		 //////////////////////////////////////////////////////////////
	     var title = document.getElementsByName('title');
		 var title_value;
		 
		 for(var i = 0; i < title.length; i++){
		    if(title[i].checked){
		        title_value = title[i].value;
		    }
		 }
		    
			if(title_value==null)
			{
				error = error + " คำนำหน้า";
				check="X";
			
			}
			else if (title_value=="etc")
			{
				var title_etc_box = document.getElementsByName('title_etc');
				var title_etc_box_value = title_etc_box.value;
				
					if(title_etc_box.value==null){
						
							error = error + " คำนำหน้าแบบกำหนดเอง";
							check="X";
						
					} 
					
			}
			//////////////////////////////////////////////////////////////
			var name_th = document.getElementById('name');
			var name_th_value = name_th.value;
			if(name_th_value=="")
			{
				error = error + " ชื่อภาษาไทย";	
				check="X";
			}
			if(patt.test(name_th_value)) { 
				
				check="X";
				error = error +"กรุณาหลีกเลี่ยงอักขะพิเศษ";
			}
			//////////////////////////////////////////////////////////////
			 
			var surname_th = document.getElementById('surname');
			var surname_th_value = surname_th.value;
			if(surname_th_value=="")
			{
				error = error + " นามสกุลภาษาไทย";	
				check="X";
			}
			if(patt.test(surname_th_value)) { 
				
				check="X";
				error = error +"กรุณาหลีกเลี่ยงอักขะพิเศษ";
			}
			 //////////////////////////////////////////////////////////////
			var gender = document.getElementsByName('gender');
			var gender_value;
			
			 for(var j = 0; j < gender.length; j++){
				    if(gender[j].checked){
				        gender_value = gender[j].value;
				    }
				 }
		
			 if(gender_value==null)
			 {
				 error = error + " เพศ";
				 check="X";
			 }
			 ///////////////////////////////////////////////
			 var select_department = document.getElementById('department');
			 var department_value = select_department.options[select_department.selectedIndex].value;
			 if(department_value=="select")
			{
				 error = error + "ภาควิชา";
				 check = "X";
			}
			//////////////////////////////////////////////
			 var date_of_birth = document.getElementById('date_of_birth');
			 var date_of_birth_value = date_of_birth.value; 
			 
			 if(date_of_birth_value=="")
			 {
				 error = error + " วันเกิด";
				 check="X";
			 }		
			 
			 /////////////////////////////////////////////
			 
				var position = document.getElementById('position');
				var position_value = position.value;
			if(position_value==""){
				 error = error + " ตำแหน่งงานบริหาร";
				 check="X";
				
			}
			 ////////////////////////////////////////////
			 
			 
			////////finally Check ///////////
			if(!error=="กรุณากรอก"){
					alert(""+error+"");
			}
			else{
			//	alert(":"+error+":");
			}
			 
			//////////////////get data///////////////////
			 var personal_id = document.getElementById('personalId');
				 personal_id_value = personal_id.value;
			if(patt.test(personal_id_value)) { 
				
				check="X";
				error = error +"กรุณาหลีกเลี่ยงอักขะพิเศษ";
			}

			var name_en = document.getElementById('name_en');
			var name_en_value = name_en.value;
			if(patt.test(name_en_value)) { 
				
				check="X";
				error = error +"กรุณาหลีกเลี่ยงอักขะพิเศษ";
			}
		
			var surname_en = document.getElementById('surname_en');
			var surname_en_value = surname_en.value;
			if(patt.test(surname_en_value)) { 
				
				check="X";
				error = error +"กรุณาหลีกเลี่ยงอักขะพิเศษ";
			}
			
			
			
		     var marital_status = document.getElementsByName('marital_status');
			 var marital_status_value;
			 
			 for(var i = 0; i < marital_status.length; i++){
			    if(marital_status[i].checked){
			        marital_status_value = marital_status[i].value;
			    }
			 }
			 
			 
			var address = document.getElementById('address');
			var address_value = address.value;
			if(patt.test(address_value)) { 
				
				check="X";
				error = error +"กรุณาหลีกเลี่ยงอักขะพิเศษ";
			}
		
			
			var tel = document.getElementById('phonenumber');
			var tel_value = tel.value;
			if(patt.test(tel_value)) { 
				
				check="X";
				error = error +"กรุณาหลีกเลี่ยงอักขะพิเศษ";
			}
			var patt_email = new RegExp("[#$%^*?!~`<>]");
			var email = document.getElementById('email');
			var email_value = email.value;
			if(patt_email.test(email_value)) { 
				
				check="X";
				error = error +"กรุณาหลีกเลี่ยงอักขะพิเศษ";
			}
			
			var facebook = document.getElementById('facebook');
			var facebook_value = facebook.value;
			if(patt.test(facebook_value)) { 
				
				check="X";
				error = error +"กรุณาหลีกเลี่ยงอักขะพิเศษ";
			}
			
		
				
		
			
			//////////////////END GET DATA //////////////////
			//alert("check:"+check);
			if(check=="")
			{
				/* AJAX */
				var xmlhttp;
				
				if(window.XMLHttpRequest) {
					// code for IE7+, Firefox, Chrome, Opera, Safari
					xmlhttp = new XMLHttpRequest();
				}
				else {
					// code for IE6, IE5
					xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
				}
				
				xmlhttp.onreadystatechange = function() {
					if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {									
					
						//alert("I'm back");
						var result = xmlhttp.responseText;
						//alert("result:"+result);
						if(result=="fail"){
							alert("บันทึกข้อมูลไม่สำเร็จกรุณาตรวจสอบข้อมูล");
							
						}
						else if(result=="success"){
							alert("บันทึกข้อมูลสำเร็จ");
							window.location="/AIMS_Project/admin_employee.jsp";
							// redirect
							
						}else{
							alert("บันทึกข้อมูลไม่สำเร็จ");
							
						}
						
						//document.location.href = "admin_account.jsp";
					}
				}
				
				var parameter = "personal_id="+personal_id_value+
								"&title_th="+title_value+
							    "&name_th="+name_th_value+
							    "&surname_th="+surname_th_value+
							    "&name_en="+name_en_value+
								"&surname_en="+surname_en_value+
								"&gender="+gender_value+
								"&marital_status="+marital_status_value+
								"&date_of_birth="+date_of_birth_value+
								"&address="+address_value+
								"&tel="+tel_value+
								"&email="+email_value+
								"&facebook="+facebook_value+
								"&department_id="+department_value+
								"&position="+position_value;
				
				//alert(parameter);
				xmlhttp.open("POST", "admin_employee_add_normal_background.jsp?"+parameter, true);
				xmlhttp.send();
			}else{
				alert("กรุณาตรวจสอบความถูกต้องอีกครั้ง");
			}
			
	});
	
});
function isValidUploadForm(oForm){
	
	//alert("Active isValidUploadForm");
	
	var _validFileExtensions = [".xlsx", ".xls"];
	  var arrInputs = oForm.getElementsByTagName("input");
	 
	  
	//  alert("arrInputs:"+ oForm.getElementsByTagName("input")[0].value);
	  
	  var file_name =  oForm.getElementsByTagName("input")[0].value
	  	if(file_name=="")
	  	{
	  		alert("กรุณาเลือกไฟล์ที่จะทำการ Import ในรูปแบบ xls, xlsx");
	  		return false;
	  	}
	  
	    for (var i = 0; i < arrInputs.length; i++) {
	        var oInput = arrInputs[i];
	        if (oInput.type == "file") {
	            var sFileName = oInput.value;
	            if (sFileName.length > 0) {
	                var blnValid = false;
	                for (var j = 0; j < _validFileExtensions.length; j++) {
	                    var sCurExtension = _validFileExtensions[j];
	                    if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
	                        blnValid = true;
	                        break;
	                    }
	                }

	                if (!blnValid) {
	                    alert("เกิดข้อผิดพลาด " + sFileName + " ไฟล์ที่แนบไม่ตรงรูปแบบของ : " + _validFileExtensions.join(", "));
	                    return false;
	                }
	            }
	        }
	    }

	    return true;
		
}
	
</script>
	
</head>
</head>
<body>

<%	
	String strUser = String.valueOf(session.getAttribute("sUser"));
	HttpSession htp_session = request.getSession();
			
	// check session
		if (htp_session == null || htp_session.getAttribute("sUser") == null) {
		    // Forward the control to login.jsp if authentication fails or session expires
		    request.getRequestDispatcher("/login.jsp").forward(request,
		        response);
		}
		if(!"admin".equals(htp_session.getAttribute("sUser"))){%>
			<script>alert("This user dont have PERMISSION to access this zone.");</script>
			<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=system_select.jsp"> 	
	<%}
		

		//set Database Connection
		String hostProps = "";
		String usernameProps  = "";
		String passwordProps  = "";
		String databaseProps = "";
		
		try {
			//get current path
			ServletContext servletContext = request.getSession().getServletContext();
			
			InputStream input = servletContext.getResourceAsStream("/properties/connectDB.properties");
			Properties props = new Properties();
			
			props.load(input);

			hostProps  = props.getProperty("host");
			usernameProps  = props.getProperty("username");
			passwordProps  = props.getProperty("password");
			databaseProps = props.getProperty("database");
		} catch (Exception e) { 
			out.println(e);  
		}
		
		// connect database
		Connection connect = null;		
		try {
			Class.forName("com.mysql.jdbc.Driver");
		
			connect =  DriverManager.getConnection("jdbc:mysql://" + hostProps  + "/" + databaseProps +
					"?user=" + usernameProps  + "&password=" + passwordProps + "&characterEncoding=tis620" );
		
			if(connect != null){
				System.out.println("Database Connect Sucesses.");
			} else {
				System.out.println("Database Connect Failed.");	
			}

		} catch (Exception e) {
			out.println(e.getMessage());
			e.printStackTrace();
		}
		
		List<Department> department = new ArrayList<Department>();
		try{
			ResultSet rs_depart = connect.createStatement().executeQuery(" SELECT *"+
																		 " FROM department ");
																		
			while(rs_depart.next())
			{
				Department dep = new Department();
				
				dep.setDepartmentNameTH(rs_depart.getString("department_name_th"));
				dep.setDepartmentId(Integer.parseInt(rs_depart.getString("department_id")));
				
				department.add(dep);
				
				
			}
			
			
		}catch(Exception x){
			out.println(x.getMessage());
			x.printStackTrace();
			
		}
		
		connect.close();
%>

	<div id="page-wrap">
		<div id="inside">
			<table border="0">
				<tr style="font-size:24px">
					<td width="600" height="100" style= "background-color: #273b80;border: 0px ;padding: 0px; 0px;" >
						<div id="header_banner-2"></div>
					</td>
					
					<td width="680" height="100" style= "background-color: #273b80;border: 0px;padding: 0px; 0px;" >
						<p align="right"><label><font size="4" color="#ffffff">username : <%=strUser%>&nbsp;&nbsp;</font></label></p>
						<a href="logout.jsp"><p align="right"><label style="cursor: pointer;"><font size="3" color="#ffffff">log out &nbsp;</font></label></p></a>
					</td>
				</tr>
			</table>
				
				<div id="main-content-ac">
					<table style="border: 0px;">
						
						<tr style="border: 0px;">
								<td style="border: 0px;">
									<div class="imageFrame">เพิ่มข้อมูลบุคลากร </div>
								</td>
								<td style="border: 0px;" class="silvergrad" id="import_excel">
									<br>
									<br> <br>
									<span title="Import By Excel"><img src="image/excel_import_icon.png" style="width:60px;height:60px;" ></span>
						
								</td>
							</tr>
						
					</table>
							
						<div id="frm_add_file">
								<center>
											<table>
												<tr>
													<td>
														<center>
															 <form method="post" onsubmit="return isValidUploadForm(this);	" action="UploadServletEmployee"enctype="multipart/form-data">
									        		  			 เลือกไฟล์ <input id="file_box" type="file" name="uploadFile"> 
									        		  			 <br>
									        		  			 <br>
									        		  			 <br>
									        		  			 
									        		  			 <input type="submit" value="Upload" />
									        		  			 
									        		  			 <br>
									        		  			 </form>
									        		  			 
									        		  	</center>
									        		 </td>
												</tr>
													
											</table>
									</center>		
				
							</div>
						
					<br/><br/><br/><br/>
	 						<center>
	 							
									<table width="900" border="1">
									
										 								  
								<form name="lecturer_save_frm" method="post">		  
										 	<tr style="font-size:24px">
				        	
								                <td width="400" height="50">
								                	<font size="5"><strong>เลขประจำตัวประชาชน</strong></font>
								                </td>
								                <td width="600" height="50">
								                	<input type="text" id="personalId" name="personalId" style="font-size:18px" value=""/>
								         		
								                </td>
				                	      
				         				   </tr>
								 
										  <tr style="font-size:24px">
								                <td height="50">
								                	<font size="5"><strong>คำนำหน้า</strong></font>
						                			<label><font size="5" color="#FF0000">*</font></label>
								                </td>
								                <td height="50">
								                	
								                      <label>
								                        <input type="radio" name="title" id="title" value="นาย" id="mr" />
								                        <font size="5">นาย</font>
								                      </label>
								                      &nbsp;&nbsp;
								                      <label>
								                        <input type="radio" name="title" id="title" value="นาง" id="mrs" />
								                        <font size="5">นาง</font>
								                      </label>
								                      &nbsp;&nbsp;
								                      <label>
								                        <input type="radio" name="title" id="title" value="นางสาว" id="miss" />
								                        <font size="5">นางสาว</font>
								                      </label>
								                      &nbsp;&nbsp;
								                      <label>
								                         <input type="radio" name="title" id="title" value="etc" id="etc" />
								                        <font size="5">อื่นๆ</font>
								                        &nbsp;
								                        <input type="text"  style="font-size:18px" size="10" id="title_etc" name="title_etc"/>
								                      </label>
						
								                </td>
		           						 </tr>
		                 				
										  	
										    <tr style="font-size:24px">
								       	         <td height="50">
								                	<font size="5"><strong>ชื่อ</strong></font>
						                			<label><font size="5" color="#FF0000">*</font></label>
								                </td>
								                <td height="50">
								                	<input name="name" id="name" type="text" style="font-size:18px" required/>
								                </td>
								            </tr>
								            
								            <tr style="font-size:24px">
								                <td height="50">
								                	<font size="5"><strong>นามสกุล</strong></font>
						                			<label><font size="5" color="#FF0000">*</font></label>
								                </td>
								                <td height="50">
								                	<input name="surname" id="surname" type="text" style="font-size:18px" required/>
								                </td>
								                
								            </tr>
								              <tr style="font-size:24px">
								                <td height="50">
								                	<font size="5"><strong>ชื่อ(ภาษาอังกฤษ)</strong></font>
						                			<label><font size="5" color="#FF0000">*</font></label>
								                </td>
								                <td height="50">
								                	<input name="name_en" id="name_en" type="text" style="font-size:18px" />
								                </td>
								            </tr>
								              <tr style="font-size:24px">
								                <td height="50">
								                	<font size="5"><strong>นามสกุล(ภาษาอังกฤษ)</strong></font>
						                			<label><font size="5" color="#FF0000">*</font></label>
								                </td>
								                <td height="50">
								                	<input name="surname_en" id="surname_en" type="text" style="font-size:18px" />
								                </td>																									
		           						 </tr>
										  
										  <tr style="font-size:24px">
								                <td height="50">
								                	<font size="5"><strong>เพศ</strong></font>
						                			<label><font size="5" color="#FF0000">*</font></label>
								                </td>
								                <td height="50">
								   
								                      <label>
								                        <input type="radio" name="gender" value="M" id="man" />
								                        <font size="5">ชาย</font></label>
								                      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
								                      <label>
								                        <input type="radio" name="gender" value="F" id="women" />
								                        <font size="5">หญิง</font></label>
								                </td>
		            						</tr>
										  
										   <tr style="font-size:24px">
								                <td height="50">
								                	<font size="5"><strong>สถานภาพ</strong></font>
								                </td>
								                <td height="50">
								   
								                      <label>
								                        <input type="radio" name="marital_status" id="marital_status" value="โสด" checked="checked" />
								                        <font size="5">โสด</font></label>
								                      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
								                      <label>
								                        <input type="radio" name="marital_status"id="marital_status" value="แต่งงาน" />
								                        <font size="5">แต่งงาน</font></label>
								                          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
								                      <label>
								                        <input type="radio" name="marital_status" id="marital_status" value="หย่าร้าง" />
								                        <font size="5">หย่าร้าง</font></label>
								                    
								                </td>
		          						  </tr>				
										  
										  <tr style="font-size:24px">
							                <td height="50">
							
							                	<font size="5"><strong>วันเกิด (ว/ด/ป)</strong></font>
							                	<label><font size="5" color="#FF0000">*</font></label>
							                </td>
					
							                 <td height="50">
							                   <input type="date" id="date_of_birth" name="date_of_birth" style="font-size: 18px;" required />
							                </td>
							            </tr>
							                
							            <tr style="font-size:24px">
							                <td height="50">
												<font size="5"><strong>ที่อยู่</strong></font>
							                </td>
							                <td height="50">
							                	<input name="address" id="address" type="text" style="font-size:18px" />
							                </td>
							           </tr>
							                
										<tr style="font-size:24px">
							                <td height="50">
							                	<font size="5"><strong>เบอร์โทรศัพท์</strong></font>
							                </td>
							                <td height="50">
							                	<input name="phonenumber" id="phonenumber" type="text" style="font-size:18px" />
							                </td>
							            </tr>
							
										<tr style="font-size:24px">
							                <td height="50">
												<font size="5"><strong>E-mail</strong></font>
							                </td>
							                <td height="50">
							                	<input name="email" id="email" type="text" style="font-size:18px" />
							                </td>
							             </tr>
							
										<tr style="font-size:24px">
							                <td height="50">
												<font size="5"><strong>Facebook</strong></font>
							                </td>
							                <td height="50">
							                	<input name="facebook" id="facebook" type="text" style="font-size:18px" />
							                </td>
							            </tr>
							
										  
										  <tr style="font-size:20px">
											<td>
													<font size="5">ภาควิชา</font>
						                			<label><font size="5" color="#FF0000">*</font></label>
						                	</td>
											<td>
													<select name="department" id="department" style="font-size: 18px;">
													<option value="select">Select</option>
													<option value="no">ไม่สังกัดภาควิชา</option>
							  		
											  		<%
													for(Department dept : department) {
														if(dept.getDepartmentId() == 0) {}
														else {
													%>
														<option value="<%=dept.getDepartmentId()%>" id="<%=dept.getDepartmentId()%>"><%=dept.getDepartmentNameTH()%></option>	
													<%				
														}
													}
													%>
													</select>
											</td>           
										  </tr>
										 
										    <tr style="font-size:20px">
										   	 <td>
										   	 		<font size="5">ตำแหน่งงาน</font>
						                			<label><font size="5" color="#FF0000">*</font></label>
						                		</td>
											 <td>
											 		<input name="position" id="position" type="text" style="font-size:18px" />
											 </td>
										   </tr>
										  
										  
										  <tr style="font-size:20px">
											<td>
													<font size="5">สถานะ</font>
						                			<label><font size="5" color="#FF0000">*</font></label>
						                			</td>
											<td>
												<select name="status" id="status" style="font-size: 18px;" >
													<option value="ปกติ">ปกติ</option>
													<option value="ลาออก">ลาออก</option>
													<option value="อื่นๆ">อื่นๆ</option>
												</select>
											</td>           
										  </tr>
										  
										  <tr>
							            	<td colspan="2">
							            		<label><font size="3" color="#FF0000">หมายเหตุ: * คือ ข้อมูลสำคัญ จำเป็นต้องกรอก</font></label>
							            	</td>
							            </tr>
							            
										  <tr style="font-size:24px">
							              	  <td height="50">
							                	<center><input type="button" name="save" id="save"  value="save" class="buttonStyle"/></center>
							                </td>
		           				</form>   <!-- End lecturer_save_frm  -->
							                <td height="50">
							                	<center><a href="admin_employee.jsp"><button class="buttonStyle">cancel</button></a></center>
							                </td>
		          						  </tr>
											  
										 
									</table>

						</center>
	 					
						<br><br><br>
				
			<div style="clear: both;"></div>
				
			<div id="footer"></div>
			
		</div>		
			<div style="clear: both;"></div>		
   </div>

</body>
</html>